#!/usr/bin/perl -w
# And then my favorite do_GET routine:
use LWP; # loads lots of necessary classes.
use strict;
use Encode;
use HTML::TreeBuilder 3; 
use Getopt::Std;
use WWW::Mechanize;

my $browser;
my %option;
my $find_all_sites = 1;
getopts('s:c:h', \%option) || usage_quit(1);
usage_quit(0) if $option{'h'} ;
 
sub usage_quit {
  # Emit usage message, then exit with given error code.
  print <<"END_OF_MESSAGE"; exit($_[0] || 0);
Usage:
$0  [switches]  
     
Switches:
 -h        display this help message
 -s		   the stock code 
 -c		   the company from which this program get information
END_OF_MESSAGE
}
my $stock_code = $option{'s'};

my $company_code = $option{'c'};
print $company_code . "\n";
my %sites = (
	GOV => {
		HaSTC => "http://hastc.org.vn/InfoShow/OnlineShareContinuousData.aspx",
		HoSTC => "http://www.vse.org.vn/ls_vse/"
	},
	SSI => {
		HaSTC => "http://ssi.com.vn/ShowPrice/Data/Data_HaSTC.htm",
		HoSTC => "http://ssi.com.vn/ShowPrice/Data/Data.htm"
	},
	TSC => {
		HaSTC => "http://www.thanglongsc.com.vn/hastc",
		HoSTC => "http://www.thanglongsc.com.vn/hostc"
	},
	BSC => {
		HaSTC => "http://www.bsc.com.vn/OP/Requester.htm?i=" . time ,
		HoSTC => "http://www.bsc.com.vn/OP/Requester.htm?i=" . time
	}	 
);

if($company_code eq '' || $company_code eq ' '){
	$company_code = 'GOV';
}
my $ha_found = 0;
my $ho_found = 0;
my $ho_stock_info = '';
my $ha_stock_info = '';
foreach my $key (keys %sites){
	last if $ha_found || $ho_found;
	if (!$find_all_sites){
		if ($key eq $company_code){
			($ha_found, $ha_stock_info) = fetch_stock_info($stock_code, $sites{$key}{'HaSTC'});
			if(!$ha_found){
				($ho_found, $ho_stock_info) = fetch_stock_info($stock_code, $sites{$key}{'HoSTC'});
			}
			if(!$ha_found && !$ho_found){
				print "The specified stock code doesn't exsit \n";
				exit;
			}else{
				if($ha_found){
					print $ha_stock_info;
				}
				if($ho_found){
					print $ho_stock_info;
				}	
			}
		}
	}else{
			($ha_found, $ha_stock_info) = fetch_stock_info($stock_code, $sites{$key}{'HaSTC'});
			if(!$ha_found){
				($ho_found, $ho_stock_info) = fetch_stock_info($stock_code, $sites{$key}{'HoSTC'});
			}
			if(!$ha_found && !$ho_found){
				print "The specified stock code doesn't exsit \n";
				exit;
			}else{
				if($ha_found){
					print $ha_stock_info;
				}
				if($ho_found){
					print $ho_stock_info;
				}
			}
	}
}
sub fetch_stock_info{
	my ($s_code, $c_url) = @_;

	my $found = 0;
	my $stock_info = '';
	
	my ($html, $status, $is_success) = do_GET($c_url);
	if (!$is_success){
		print $status . "\n";
		exit;	
	}
	
	my $root = HTML::TreeBuilder->new_from_content(Encode::decode_utf8($html));
	$root->eof();
	# If the page has chkAll option, checked it and resubmit form		
	
	
	my @tables = $root->find_by_tag_name('table');
	# Find the table that has maximum number of childs
	my $table_idx = 0;
	my $max_children_number = 0;
	my $idx = 0;
	for ($idx=0; $idx< @tables; $idx++){
		my @child_nodes = $tables[$idx]->content_list();
		if(uc($child_nodes[0]->tag()) eq "TBODY" ){
			$tables[$idx] = $child_nodes[0];
			@child_nodes = $tables[$idx]->content_list();
		}
		if(@child_nodes > $max_children_number){
			$max_children_number = @child_nodes;
			$table_idx = $idx;
			
		}
	}
	if($max_children_number > 0){
		#print "The largest table is " . $table_idx . " and the index is " . $idx . " with " . $max_children_number ." children \n";
		foreach my $tr_node ($tables[$table_idx]->content_list){
			if($tr_node->as_text() =~ /$stock_code/){
				$found = 1;
				$stock_info .= $tr_node->as_HTML();
			}
		}		
	}
	
	#$root->dump;
	$root->delete();
	return ($found, $stock_info) if wantarray;
}


sub do_GET {	  
	  $browser = WWW::Mechanize->new(
	  	agent => 'Mozilla/5.0 (compatible; MSIE 4.01; Windows95)'	  	
	  ) unless $browser;
	  $browser->parse_head(0);	  
	  my $resp = $browser->get(@_);  
	  return ($resp->content, $resp->status_line, $resp->is_success, $resp)
	    if wantarray;
	  return unless $resp->is_success;
	  return $resp->content;
}